import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogAnalyzer {
    private static final Logger logger = LoggerFactory.getLogger(LogAnalyzer.class);

    // 配置日志文件路径
    private static final String LOG_FILE_PATH = "./logs/bifromq.log";

    // 定义日志格式的正则表达式
    private static final Pattern logPattern = Pattern.compile(
        "(\\d{2}:\\d{2}:\\d{2}\\.\\d{3}) \\[(.*?)\\] (\\w+) (.*?) - (.*)");

    // 定义错误模式的正则表达式
    private static final Pattern errorPattern = Pattern.compile(".*(Exception|Error).*");
    private static final Pattern messageLostPattern = Pattern.compile(".*MessageLost.*");
    private static final Pattern messageDelayPattern = Pattern.compile(".*MessageDelay.*");
    private static final Pattern messageErrorPattern = Pattern.compile(".*MessageError.*");
    private static final Pattern connectionIssuePattern = Pattern.compile(".*ConnectionIssue.*");

    // 报警机制
    private static AlertManager alertManager = new AlertManager();

    public static void main(String[] args) {
        logger.info("Starting Log Analyzer...");

        try (BufferedReader br = new BufferedReader(new FileReader(LOG_FILE_PATH))) {
            String line;
            while ((line = br.readLine()) != null) {
                parseLogLine(line);
            }
        } catch (IOException e) {
            logger.error("Error reading log file: {}", e.getMessage());
        }

        logger.info("Log Analyzer finished.");
    }

    private static void parseLogLine(String line) {
        Matcher matcher = logPattern.matcher(line);
        if (matcher.matches()) {
            String timestamp = matcher.group(1);
            String thread = matcher.group(2);
            String level = matcher.group(3);
            String loggerName = matcher.group(4);
            String message = matcher.group(5);

            logger.info("Parsed Log - Time: {}, Thread: {}, Level: {}, Logger: {}, Message: {}",
                timestamp, thread, level, loggerName, message);

            if (errorPattern.matcher(message).matches()) {
                handleErrorLog(timestamp, thread, loggerName, message);
            } else if (messageLostPattern.matcher(message).matches()) {
                handleMessageLostLog(timestamp, thread, loggerName, message);
            } else if (messageDelayPattern.matcher(message).matches()) {
                handleMessageDelayLog(timestamp, thread, loggerName, message);
            } else if (messageErrorPattern.matcher(message).matches()) {
                handleMessageErrorLog(timestamp, thread, loggerName, message);
            } else if (connectionIssuePattern.matcher(message).matches()) {
                handleConnectionIssueLog(timestamp, thread, loggerName, message);
            } else {
                handleOtherLog(level, timestamp, thread, loggerName, message);
            }
        } else {
            logger.warn("Unrecognized log format: {}", line);
        }
    }

    private static void handleErrorLog(String timestamp, String thread, String loggerName, String message) {
        logger.error("Error log detected: {}", message);
        alertManager.sendAlert("Critical error detected at " + timestamp + " in " + thread + ": " + message);
        // 在此添加处理错误日志的额外逻辑
    }

    private static void handleMessageLostLog(String timestamp, String thread, String loggerName, String message) {
        logger.warn("Message lost log detected: {}", message);
        alertManager.sendAlert("Message lost detected at " + timestamp + " in " + thread + ": " + message);
        // 分析潜在原因，如网络问题、Broker故障、客户端错误
        analyzeCause(message);
    }

    private static void handleMessageDelayLog(String timestamp, String thread, String loggerName, String message) {
        logger.warn("Message delay log detected: {}", message);
        alertManager.sendAlert("Message delay detected at " + timestamp + " in " + thread + ": " + message);
        // 分析潜在原因，如网络问题、资源不足
        analyzeCause(message);
    }

    private static void handleMessageErrorLog(String timestamp, String thread, String loggerName, String message) {
        logger.error("Message error log detected: {}", message);
        alertManager.sendAlert("Message error detected at " + timestamp + " in " + thread + ": " + message);
        // 分析潜在原因，如消息格式错误、客户端实现错误
        analyzeCause(message);
    }

    private static void handleConnectionIssueLog(String timestamp, String thread, String loggerName, String message) {
        logger.warn("Connection issue log detected: {}", message);
        alertManager.sendAlert("Connection issue detected at " + timestamp + " in " + thread + ": " + message);
        // 分析潜在原因，如网络问题、客户端错误、Broker故障
        analyzeCause(message);
    }

    private static void handleOtherLog(String level, String timestamp, String thread, String loggerName, String message) {
        switch (level) {
            case "INFO":
                handleInfoLog(timestamp, thread, loggerName, message);
                break;
            case "DEBUG":
                handleDebugLog(timestamp, thread, loggerName, message);
                break;
            case "TRACE":
                handleTraceLog(timestamp, thread, loggerName, message);
                break;
            default:
                logger.warn("Unknown log level: {}", level);
                break;
        }
    }

    private static void handleInfoLog(String timestamp, String thread, String loggerName, String message) {
        logger.info("Info log detected: {}", message);
        // 在此添加处理信息日志的额外逻辑
    }

    private static void handleDebugLog(String timestamp, String thread, String loggerName, String message) {
        logger.debug("Debug log detected: {}", message);
        // 在此添加处理调试日志的额外逻辑
    }

    private static void handleTraceLog(String timestamp, String thread, String loggerName, String message) {
        logger.trace("Trace log detected: {}", message);
        // 在此添加处理追踪日志的额外逻辑
    }

    private static void analyzeCause(String message) {
        if (message.contains("network")) {
            logger.info("Potential cause: Network issue");
        } else if (message.contains("Broker")) {
            logger.info("Potential cause: MQTT Broker issue");
        } else if (message.contains("client")) {
            logger.info("Potential cause: Client error");
        } else if (message.contains("config")) {
            logger.info("Potential cause: Configuration issue");
        } else {
            logger.info("Potential cause: Unknown");
        }
    }
}
